package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.logging.Handler;



/**
 * 全局异常处理
 */

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
//使用Annotations指定拦截哪一类controller方法
//@ResponseBody
public class GlobalExceptionHandler  {

    /**
     * 异常处理方法
     * @return
     */

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.error(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误！");
    }


    @ExceptionHandler(CustomException.class)
    public R<String> CustomExceptionexception(CustomException e){
        log.info(e.getMessage());
        return  R.error(e.getMessage());
    }
}
